/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Duy
 */
@WebServlet(name = "GetWordServlet", urlPatterns = {"/GetWordServlet"})
public class GetWordServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        try {
            String pathindex = request.getRealPath("Database\\anhviet109K.index");
            String pathdict = request.getRealPath("Database\\anhviet109K.dict");
            String contentInDict = "";
            String fIndexString = readFileAsString(pathindex);
            String fDictString = readFileAsString(pathdict);
            String word = request.getParameter("findword").trim();
            System.out.println(word);
            if (word != null) {
                int indexOfWord = fIndexString.indexOf(word);
                char as9 = (char) 9;
                char as10 = (char) 10;
                int beginOfPos = fIndexString.indexOf(as9, indexOfWord);
                int endOfPos = fIndexString.indexOf(as9, beginOfPos + 1);
                int endOfCont = fIndexString.indexOf(as10, endOfPos + 1);


                String posOfWordInDict = fIndexString.substring(beginOfPos, endOfPos);
                String contOfWordInDict = fIndexString.substring(endOfPos, endOfCont);
                System.out.println("Vi tri và do dai trong file INDEX: " + posOfWordInDict + "==" + contOfWordInDict);

                String pDec = posOfWordInDict.trim();
                String cDec = contOfWordInDict.trim();
                int posOfWordInDictDec = (int) GetDemicalValue(pDec);
                int contOfWordInDictDec = (int) GetDemicalValue(cDec);
                contentInDict = fDictString.substring(posOfWordInDictDec, posOfWordInDictDec + contOfWordInDictDec);
                System.out.println("Noi dung trong file DICT: " + contentInDict);
            }
            request.setAttribute("stringMean", contentInDict);
            request.setAttribute("findword", word);
            request.getRequestDispatcher("show.jsp").forward(request, response);
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
    }

    private double GetDemicalValue(String str) {

        String base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        double decValue = 0;
        double str_length = str.length();
        for (int i = 0; i < str_length; i++) {
            char char_at = str.charAt(i);
            int pos_of_char = base64.indexOf(char_at);
            decValue = decValue + Math.pow(64, str_length - 1 - i) * pos_of_char;
        }
        return decValue;
    }

    private String readFileAsString(String filePath)
            throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);

        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();

    }

    private String readFileAsString2(String filePath)
            throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        List<String> Mylist = new ArrayList<String>();

        String contents = "";
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            Mylist.add(readData);
            buf = new char[1024];
        }
        reader.close();
        String[] s1 = Mylist.toArray(new String[0]);
        for (int i = 0; i < s1.length; ++i) {
            contents = s1[i];
        }
        return contents;

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
